package com.xyf.sys.service.impl;

import com.xyf.sys.config.CustomException;
import com.xyf.sys.domain.UserOrderEvent;
import com.xyf.sys.enums.LogisticsEventEnum;
import com.xyf.sys.mapper.SysUserOrderEventMapper;
import com.xyf.sys.service.IUserOrderEventService;
import com.xyf.sys.vo.UserEventStatistic;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * @Author R-H
 * @Date 2024/5/11606
 * @Description
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class IUserOrderEventServiceImpl implements IUserOrderEventService {


    @Autowired
    private SysUserOrderEventMapper mapper;

    @Override
    public List<UserOrderEvent> list(String dictType) {
        return null;
    }

    @Override
    public boolean addUserData(String userId, Long deptId, String orderId, String orderProductId, Integer type) {
        UserOrderEvent record = mapper.selectByDeptIdAndOrderIdAndOrderProductIdAndType(deptId, orderId, orderProductId, type);
        if (record == null) {
            record = new UserOrderEvent();
            record.setOrderId(orderId.toUpperCase());
            record.setOrderProductId(orderProductId);
            record.setUserId(userId);
            record.setDelFlag(userId);
            record.setType(type);
            record.setDeptId(deptId);
            record.setCode(generateCode(userId, type));
            record.setStatus("0");
            record.setDelFlag("0");
            record.setCreateBy(userId);
            record.setCreateTime(new Date());
            return mapper.insert(record) > 0;
        }
        throw new CustomException("该订单已添加");
    }

    @Override
    public List<UserOrderEvent> getUserData(String userId, String status) {
        return mapper.selectList(userId, status == null ? "0" : status, null);
    }

    @Override
    public List<UserOrderEvent> getUserData(String userId, String status, Integer eventType) {
        return mapper.selectList(userId, status == null ? "0" : status, eventType);
    }

    @Override
    public List<UserOrderEvent> getUserData(Long deptId, String status) {
        return mapper.selectListByDept(deptId, status == null ? "0" : status, null);
    }

    @Override
    public List<UserOrderEvent> getUserData(Long deptId, String status, Integer eventType) {
        return mapper.selectListByDept(deptId, status == null ? "0" : status, eventType);
    }

    @Override
    public boolean removeUserData(Long id, String userId, Long deptId) {
        UserOrderEvent record = mapper.selectByPrimaryKey(id);
        if (record == null) {
            throw new CustomException("数据异常");
        }
        boolean bool = mapper.deleteByPrimaryKey(record.getId()) > 0;
        List<UserOrderEvent> userData = this.getUserData(deptId, "0");
        for (UserOrderEvent event : userData) {
            long code = Long.parseLong(event.getCode());
            if (event.getType().equals(record.getType()) && code > Long.parseLong(record.getCode())) {
                event.setCode(String.format("%03d", code - 1));
                event.setUpdateBy(userId);
                mapper.updateByPrimaryKey(event);
            }
        }
        return bool;
    }

    @Override
    public boolean clear(String userId, Long deptId) {
        List<UserOrderEvent> list = getUserData(deptId, null);
        if (CollectionUtils.isEmpty(list)) {
            return false;
        }
        for (UserOrderEvent event : list) {
            event.setStatus("1");
            event.setUpdateBy(userId);
            event.setUpdateTime(new Date());
            mapper.updateByPrimaryKeySelective(event);
        }
        return true;
    }

    @Override
    public int count(String userId, Integer type) {
        return mapper.countByUserIdAndType(userId, type);
    }

    @Override
    public String generateCode(String userId, Integer type) {
        return String.format("%03d", this.count(userId, type) + 1);
    }

    @Override
    public void lastEvent(String orderId, String orderProductId, Integer eventType) {
        UserOrderEvent event = mapper.selectByOrderIdAndOrderProductIdAndType(orderId, orderProductId, eventType);
        if (event == null) {
            throw new CustomException("数据异常");
        }
        event.setStatus("2");
        event.setUpdateTime(new Date());
        mapper.updateByPrimaryKeySelective(event);
    }

    @Override
    public List<UserEventStatistic> statistic(String userId, Long deptId) {
        return mapper.selectByDeptIdAndStatus(deptId, "1");
    }

    @Override
    public void addInitEvent(String userId, Long deptId, String orderId, String orderProductId) {
        UserOrderEvent record = mapper.selectByOrderIdAndOrderProductIdAndType(orderId, orderProductId, 1);
        if (record == null) {
            record = new UserOrderEvent();
            record.setOrderId(orderId.toUpperCase());
            record.setOrderProductId(orderProductId);
            record.setUserId(userId);
            record.setDeptId(deptId);
            record.setType(1);
            record.setCode(generateCode(userId, 1));
            record.setStatus("1");
            record.setDelFlag("0");
            record.setCreateBy(userId);
            record.setCreateTime(new Date());
            mapper.insert(record);
        }
        record.setUpdateBy(userId);
        record.setUpdateTime(new Date());
        mapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public void verify(String roleKey, Integer type) {
        /*if (LogisticsEventEnum.PICKUP.getType().equals(type) && !"DRIVER".equals(roleKey)) {
            throw new CustomException("无权限");
        }
        if (LogisticsEventEnum.TRANSIT.getType().equals(type) && !"SUPPLIER".equals(roleKey) && !"SCANNER".equals(roleKey)) {
            throw new CustomException("无权限");
        }
        if (LogisticsEventEnum.FACTORY_PICKUP.getType().equals(type) && !"SUPPLIER".equals(roleKey) && !"SCANNER".equals(roleKey)) {
            throw new CustomException("无权限");
        }
        if (LogisticsEventEnum.FACTORY_COMPLETE.getType().equals(type) && !"DRIVER".equals(roleKey)) {
            throw new CustomException("无权限");
        }
        if (LogisticsEventEnum.DELIVERY.getType().equals(type) && !"REGIMENT".equals(roleKey)) {
            throw new CustomException("无权限");
        }
        if (LogisticsEventEnum.STATION.getType().equals(type) && !"REGIMENT".equals(roleKey)) {
            throw new CustomException("无权限");
        }*/
        if (LogisticsEventEnum.PICKUP.getType().equals(type) && !"SUPPLIER".equals(roleKey) && !"SCANNER".equals(roleKey)) {
            throw new CustomException("无权限");
        }
        if (LogisticsEventEnum.FACTORY_PICKUP.getType().equals(type) && !"SUPPLIER".equals(roleKey) && !"SCANNER".equals(roleKey)) {
            throw new CustomException("无权限");
        }
        if (LogisticsEventEnum.FACTORY_COMPLETE.getType().equals(type) && !"REGIMENT".equals(roleKey)) {
            if ("SCANNER".equals(roleKey)){
                throw new CustomException("已出库");
            }
            throw new CustomException("无权限");
        }
        if (LogisticsEventEnum.STATION.getType().equals(type) && !"REGIMENT".equals(roleKey)) {
            throw new CustomException("无权限");
        }
    }

    @Override
    public void verifyUniformity(String userId, int type) {
        List<UserOrderEvent> userData = this.getUserData(userId, "0");
        if (!CollectionUtils.isEmpty(userData)){
            if (userData.stream().filter(e -> type != e.getType()).findAny().isPresent()) {
                throw new CustomException("请先提交或删除已扫码列表订单后再操作");
            }
        }
    }

    @Override
    public void verifyUniformity(Long deptId, int type) {
        List<UserOrderEvent> userData = this.getUserData(deptId, "0");
        if (!CollectionUtils.isEmpty(userData)){
            if (userData.stream().filter(e -> type != e.getType()).findAny().isPresent()) {
                throw new CustomException("请先提交或删除已扫码列表订单后再操作");
            }
        }
    }

    @Override
    public UserOrderEvent getUserOrderEvent(String userId, Long deptId, String orderId, String orderProductId, Integer type, String status) {
//        return mapper.selectByUserIdAndOrderIdAndOrderProductIdAndStatusAndType(userId, orderId, orderProductId, type, status);
        return mapper.selectByDeptIdAndOrderIdAndOrderProductIdAndStatusAndType(deptId, orderId, orderProductId, type, status);
    }

    @Override
    public void update(UserOrderEvent orderEvent) {
        mapper.updateByPrimaryKeySelective(orderEvent);
    }
}
